<template>
    <div class="snake-game">
      <div class="game-header">
        <h2>贪吃蛇游戏</h2>
        <div class="score">得分: {{ score }}</div>
      </div>
      
      <div class="game-container" 
           :style="{ width: `${gridSize * cellSize}px`, height: `${gridSize * cellSize}px` }"
           tabindex="0"
           @keydown="handleKeyPress"
           ref="gameContainer">
        <!-- 蛇身 -->
        <div v-for="(segment, index) in snake" 
             :key="index" 
             class="snake-segment"
             :style="getPositionStyle(segment)">
        </div>
        
        <!-- 食物 -->
        <div class="food" :style="getPositionStyle(food)"></div>
      </div>
  
      <div class="controls">
        <van-button type="primary" @click="startGame" :disabled="isPlaying">开始游戏</van-button>
        <van-button type="danger" @click="resetGame" :disabled="!isPlaying">重新开始</van-button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import { showToast } from 'vant';
  
  // 游戏配置
  const gridSize = 20; // 网格大小
  const cellSize = 20; // 单元格大小
  const initialSpeed = 200; // 初始速度（毫秒）
  
  // 游戏状态
  const snake = ref([]);
  const food = ref({ x: 0, y: 0 });
  const direction = ref('right');
  const score = ref(0);
  const isPlaying = ref(false);
  const gameInterval = ref(null);
  const gameContainer = ref(null);
  
  // 初始化游戏
  const initGame = () => {
    // 初始化蛇的位置（从中间开始）
    snake.value = [
      { x: Math.floor(gridSize / 2), y: Math.floor(gridSize / 2) },
      { x: Math.floor(gridSize / 2) - 1, y: Math.floor(gridSize / 2) },
      { x: Math.floor(gridSize / 2) - 2, y: Math.floor(gridSize / 2) }
    ];
    
    generateFood();
    score.value = 0;
    direction.value = 'right';
  };
  
  // 生成食物
  const generateFood = () => {
    let newFood;
    do {
      newFood = {
        x: Math.floor(Math.random() * gridSize),
        y: Math.floor(Math.random() * gridSize)
      };
    } while (snake.value.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    
    food.value = newFood;
  };
  
  // 获取位置样式
  const getPositionStyle = (position) => {
    return {
      left: `${position.x * cellSize}px`,
      top: `${position.y * cellSize}px`,
      width: `${cellSize}px`,
      height: `${cellSize}px`
    };
  };
  
  // 处理键盘事件
  const handleKeyPress = (event) => {
    if (!isPlaying.value) return;
    
    const keyMap = {
      'ArrowUp': 'up',
      'ArrowDown': 'down',
      'ArrowLeft': 'left',
      'ArrowRight': 'right'
    };
    
    const newDirection = keyMap[event.key];
    if (!newDirection) return;
    
    // 防止反向移动
    const opposites = {
      'up': 'down',
      'down': 'up',
      'left': 'right',
      'right': 'left'
    };
    
    if (opposites[newDirection] !== direction.value) {
      direction.value = newDirection;
    }
  };
  
  // 移动蛇
  const moveSnake = () => {
    const head = { ...snake.value[0] };
    
    switch (direction.value) {
      case 'up': head.y--; break;
      case 'down': head.y++; break;
      case 'left': head.x--; break;
      case 'right': head.x++; break;
    }
    
    // 检查碰撞
    if (isCollision(head)) {
      gameOver();
      return;
    }
    
    snake.value.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.value.x && head.y === food.value.y) {
      score.value += 10;
      generateFood();
    } else {
      snake.value.pop();
    }
  };
  
  // 检查碰撞
  const isCollision = (head) => {
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
      return true;
    }
    
    // 检查自身碰撞
    return snake.value.some(segment => segment.x === head.x && segment.y === head.y);
  };
  
  // 开始游戏
  const startGame = () => {
    if (isPlaying.value) return;
    
    initGame();
    isPlaying.value = true;
    gameContainer.value.focus();
    
    gameInterval.value = setInterval(() => {
      moveSnake();
    }, initialSpeed);
  };
  
  // 重置游戏
  const resetGame = () => {
    clearInterval(gameInterval.value);
    isPlaying.value = false;
    initGame();
  };
  
  // 游戏结束
  const gameOver = () => {
    clearInterval(gameInterval.value);
    isPlaying.value = false;
    showToast('游戏结束！得分：' + score.value);
  };
  
  // 组件挂载时初始化
  onMounted(() => {
    initGame();
  });
  
  // 组件卸载时清理
  onUnmounted(() => {
    clearInterval(gameInterval.value);
  });
  </script>
  
  <style scoped>
  .snake-game {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background-color: #f7f8fa;
    min-height: 100vh;
  }
  
  .game-header {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .score {
    font-size: 24px;
    font-weight: bold;
    color: #1989fa;
    margin-top: 10px;
  }
  
  .game-container {
    position: relative;
    background-color: #fff;
    border: 2px solid #1989fa;
    border-radius: 4px;
    outline: none;
  }
  
  .snake-segment {
    position: absolute;
    background-color: #1989fa;
    border-radius: 2px;
  }
  
  .food {
    position: absolute;
    background-color: #ee0a24;
    border-radius: 50%;
  }
  
  .controls {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }
  </style>